package com.app.mp3player;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.app.mp3player.adapter.Mp3ListAdapter;
import com.app.mp3player.model.Mp3Info;
import com.app.mp3player.service.DownLoadService;
import com.app.utils.AppConstant;
import com.app.utils.FileUtils;
import com.app.utils.HttpUtil;

public class Mp3ListActivity extends ListActivity {
	
	private static final String TAG = "Mp3ListActivity";
	
	private List<Mp3Info> mp3Infos;
	private Mp3ListAdapter adapter;
	private int type;
	private ScanSdReceiver scanSdReceiver = null;
	private IntentFilter intentfilter = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mp3_list);
		Intent intent = getIntent();
		type = intent.getIntExtra("type", 5);
		
		Resources res = getResources();
		if(type == MainActivity.REMOTE){
			setTitle(res.getString(R.string.remote_music_text));
			mp3Infos = getMp3List();
		}else{
			setTitle(res.getString(R.string.local_music_text));
			scanSdCard();
			FileUtils fileUtils = new FileUtils();
			mp3Infos = fileUtils.getMp3Files(this,"mp3");
		}
		adapter = new Mp3ListAdapter(this, mp3Infos);
		setListAdapter(adapter);
	}

	
	
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Mp3Info info = mp3Infos.get(position);
		if(null != info){
			//远程就下载，本地就播放
			if(type == MainActivity.REMOTE){
				downLoadMp3(info);
			}else{
				Intent intent = new Intent(Mp3ListActivity.this, PlayActivity.class);
				intent.putExtra("mp3Info", info);
				System.out.println("onListItemClick-------->"+info.toString());
				startActivity(intent);
			}
		}
	}
	
	/**
	 * 下载MP3 信息
	 * @param info
	 */
	public void downLoadMp3(Mp3Info info){
		Intent intent = new Intent();
		intent.putExtra("mp3Info", info);
		intent.setClass(this, DownLoadService.class);
		startService(intent);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.mp3_list, menu);
		return true;
	}

	/**
	 * 获取Mp3列表
	 * @return
	 */
	public List<Mp3Info> getMp3List(){
		String dataStr = requestMp3Info(AppConstant.URL.BASE_URL+"mp3list.php");
		return parser(dataStr);
	}
	
	/**
	 * 获取远程MP3
	 * @param url
	 * @return
	 */
	public String requestMp3Info(String url){
		String retStr = HttpUtil.queryStringForGet(url);
		return retStr;
	}
	
	/**
	 * 解析json字符串
	 * @return
	 */
	public List<Mp3Info> parser(String jsonStr){
		List<Mp3Info> tempList = new ArrayList<Mp3Info>();
		try {
			JSONArray jsonArray = new JSONArray(jsonStr);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject el = (JSONObject)jsonArray.get(i);
				Mp3Info mp3Info = new Mp3Info(el.getString("name"),
						el.getInt("size") + "", el.getString("lrcName"),
						el.getInt("lrcSize") + "", el.getString("author"),
						el.getInt("duration"));
				tempList.add(mp3Info);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.e(TAG, "json解析失败");
		}
		return tempList;
	}
	
	

	@Override
	protected void onResume() {
		if(intentfilter == null){
			intentfilter = new IntentFilter( Intent.ACTION_MEDIA_SCANNER_STARTED);
		}
		intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        intentfilter.addDataScheme("file");
        scanSdReceiver = new ScanSdReceiver();
        registerReceiver(scanSdReceiver, intentfilter);
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if(scanSdReceiver != null){
			unregisterReceiver(scanSdReceiver);
		}
		super.onDestroy();
	}
	
	public void scanSdCard(){
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath()))); 
	}
	
	public class ScanSdReceiver extends BroadcastReceiver {
		 
	    private AlertDialog.Builder  builder = null;
	    private AlertDialog ad = null;
	    private int count1;
	    private int count2;
	    private int count;
	    @Override
	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)){
	            Cursor c1 = context.getContentResolver()
	            .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
	                    new String[]{MediaStore.Audio.Media.TITLE,
	                    MediaStore.Audio.Media.DURATION,
	                    MediaStore.Audio.Media.ARTIST,
	                    MediaStore.Audio.Media._ID,
	                    MediaStore.Audio.Media.DISPLAY_NAME },
	                    null, null, null);
	            count1 = c1.getCount();
	            System.out.println("count:"+count);
	            builder = new AlertDialog.Builder(context);
	            builder.setMessage("正在扫描存储卡...");
	            ad = builder.create();
	            ad.show();
	             
	        }else if(Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)){
	            Cursor c2 = context.getContentResolver()
	            .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
	                    new String[]{MediaStore.Audio.Media.TITLE,
	                    MediaStore.Audio.Media.DURATION,
	                    MediaStore.Audio.Media.ARTIST,
	                    MediaStore.Audio.Media._ID,
	                    MediaStore.Audio.Media.DISPLAY_NAME },
	                    null, null, null);
	            count2 = c2.getCount();
	            count = count2-count1;
	            ad.cancel();
	            if (count==0){
	                Toast.makeText(context,"共增加"+ 
	                        count+"首歌曲", Toast.LENGTH_LONG).show();
	            } else {
	                Toast.makeText(context,"共减少"+
	                        count + "首歌曲", Toast.LENGTH_LONG).show();
	            }   
	            FileUtils fileUtils = new FileUtils();
				mp3Infos = fileUtils.getMp3Files(Mp3ListActivity.this,"mp3");
				adapter.notifyDataSetChanged();
	        }   
	    }
	}
	
	
}
